package cn.itlaobing.dao;
import cn.itlaobing.entity.OrderEntity;
import cn.itlaobing.entity.OrderStatus;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by admin on 2017/11/6.
 */
public class OrderDao extends BaseDao{
    public List<OrderEntity> selectByOrderid(Long userid)throws SQLException{
        String sql="SELECT * FROM orders WHERE userid=? order by ordertime desc";
        QueryRunner qr=new QueryRunner(getDataSource());
        BeanListHandler<OrderEntity> beanListHandler=new BeanListHandler<OrderEntity>(OrderEntity.class);
        return  qr.query(sql,beanListHandler,userid);
    }
    //判断订单的状态
    public OrderEntity pay(String orderid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(getDataSource());
        String sql = "select * from orders where orders=? ";
        BeanHandler<OrderEntity> beanHandler=new BeanHandler<OrderEntity>(OrderEntity.class);
        OrderEntity orderEntity=queryRunner.query(sql,beanHandler,orderid);
        if (orderEntity==null){
            return null;
        }
        //改变订单的状态
        if (orderEntity.getOrderStatus()== OrderStatus.NO_PAYMENT){
            sql="update orders set orderstatus=? where id=?";
            queryRunner.update(sql,OrderStatus.ALLOCATE.name(),orderEntity.getOrderid());
            orderEntity.setOrderStatus(OrderStatus.ALLOCATE);
            return orderEntity;
        }
        return  null;
    }
}
